import React, { PureComponent } from 'react';
import { connect } from "dva"
import { Form, Button, Icon, Table, Modal } from 'antd';
import ToolConfigModals from '../../components/toolConfigModals';
import StructureTree from "../../components/forms/structureTree"
import { worker } from "../../utils/worker"
import {cloneDeep} from "lodash"
import "../../Common.less"
import "./index.less"
class CusProps extends PureComponent {
    constructor(props) {
        super(props)
        this.state = {
            selectedKeys: [],
            selectedRowKeys: [],
            expandedKeys: [],
            data: [],
            tloading:false,
        }
        this.onSelectChange = this.onSelectChange.bind(this)
        this.editCusProps = this.editCusProps.bind(this)
        this.deleteCusProps = this.deleteCusProps.bind(this)
        this.onSelect = this.onSelect.bind(this)
        this.getData = this.getData.bind(this)
        this.addCusProp = this.addCusProp.bind(this)
        this.modalConfirm = this.modalConfirm.bind(this)
        this.massDelete = this.massDelete.bind(this)
        this.refresh=this.refresh.bind(this)
    }
    modalConfirm() {//
        const {modalContext}=this.state;
        if (modalContext && modalContext.context && modalContext.context.refresh) {
            modalContext.context.refresh()
        }
    }
    onSelectChange = selectedRowKeys => {
        this.setState({ selectedRowKeys });
    };
    onSelect(keys, e) {
        let { id, parentName,parentId, treeLeaf } = e.node.props;
        if (treeLeaf == 0) {
            this.setState({
                definitionTreeId: id,
                parentId:parentId,
                definitionTreeName: parentName
            })
        }else{
            this.setState({
                definitionTreeId: null,
                parentId:null,
                definitionTreeName: null
            })
        }
        this.setState({
            selectedKeys: keys,
            selectedRowKeys: []
        })
        this.getData({
            definitionPartId: id
        })
    }
    editCusProps(e, item) {
        e.preventDefault();
        const { definitionTreeId,parentId, definitionTreeName } = this.state;
        if (this.state.modalContext) {
            this.state.modalContext.updateModal({
                visible: true,
                title: "属性编辑",
                event: { code: 'cusPropsEdit' },
                extra: {
                    mode: "edit",
                    propData: item,
                    definitionTreeId,
                    parentId,
                    definitionTreeName
                }
            });
        }
    }
    async getData(extra) {
        this.setState({
            tloading:true
        })
        const { treeData } = this.state;
        const { definitionTreeId } = this.state;
        let res = await this.props.cusPropsList(extra ? { definitionPartId: definitionTreeId, ...extra } : { definitionPartId: definitionTreeId })
        if (res && res.length) {
            for (let i = 0; i < res.length; i++) {
                let item = res[i];
                const obj = await worker.getTreeNode(treeData, item.definitionPartId)
                const obj2 = await worker.getTreeNode(treeData, item.definitionTreeId)
                item.definitionPartName = obj?obj.title:""
                item.definitionTreeName = obj2?obj2.title:""
            }
        }
        this.setState({
            data: res,
            tloading:false
        })
    }
    massDelete(e) {
        e.preventDefault();
        Modal.confirm({
            title: "提示",
            content: "是否删除选中的自定义属性?",
            okText:"确定",
            cancelText:"取消",
            onOk:()=>{
                const { selectedRowKeys } = this.state;
                this.props.deleteCusProps({ propertyIds: selectedRowKeys }, res => {
                    this.getData()
                }, err => {

                })
            },
            onCancel() {

            }
        })

    }
    deleteCusProps(e, item) {
        e.preventDefault();
        Modal.confirm({
            title: "提示",
            content: "是否删除选中构件属性?",
            okText:"确定",
            cancelText:"取消",
            onOk:()=>{
                this.props.deleteCusProps({ propertyIds: [item.id] }, res => {
                    this.getData()
                }, err => {

                })
            },
            onCancel() {

            }
        })

    }
    async componentDidMount() {
        const { dictlist } = this.props;
        let res = await this.props.getStructureTree()
        let resc = cloneDeep(await worker.loopTreeNode2(res,null,null,true))
        if (resc) {
            this.setState({
                expandedKeys: resc.map(item => item.key),
                treeData: resc
            })
        }

        this.setState({
            isShowList: dictlist.filter(item => item.dictType == "is_show"),
            isEffectiveList: dictlist.filter(item => item.dictType == "is_effective"),
            isRequiredList: dictlist.filter(item => item.dictType == "is_required"),
            propertyTypeList: dictlist.filter(item => item.dictType == "property_type"),
            unitList: dictlist.filter(item => item.dictType == "unit"),
            isCalculateList: dictlist.filter(item => item.dictType == "is_calculate"),

        })
        this.getData()
    }
    addCusProp(e) {
        const { definitionTreeId, definitionTreeName,parentId } = this.state;
        e.preventDefault();
        if (this.state.modalContext) {
            this.state.modalContext.updateModal({
                visible: true,
                title: "属性编辑",
                event: { code: 'cusPropsEdit' },
                extra: {
                    mode: "add",
                    definitionTreeId,
                    definitionTreeName,
                    parentId
                }
            });
        }
    }
    refresh(){
        this.setState({
            selectedRowKeys:[]
        })
        this.getData()
    }
    render() {
        const { tloading,selectedKeys, selectedRowKeys, treeData, expandedKeys, data, definitionTreeId, isShowList, isEffectiveList, propertyTypeList, unitList } = this.state;
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange,
        };
        const columns = [
            {
                title: '属性名称',
                dataIndex: 'key',
                key: 'key',
                ellipsis: true,
            },
            {
                title: '属性标识',
                dataIndex: 'name',
                key: 'name',
                ellipsis: true,
                render:text=>text.replace(/^([^\,]*).*$/,function($all,$1){return $1})
            },
            {
                title: '属性类型',
                dataIndex: 'type',
                key: 'type',
                ellipsis: true,
                render: text => propertyTypeList.find(item => item.id == text).dictLabel
            },
            {
                title: '默认值',
                dataIndex: 'defaultValue',
                key: 'defaultValue',
                width:"100px",
                ellipsis: true,
            },
            {
                title: '单位',
                dataIndex: 'unit',
                key: 'unit',
                width:"60px",
                ellipsis: true,
                render: text => unitList.find(item => item.id == text).dictLabel
            },
           
            {
                title: '所属结构',
                dataIndex: 'definitionTreeName',
                key: 'definitionTreeName',
                ellipsis: true,
            },
            {
                title: '所属部位',
                dataIndex: 'definitionPartName',
                key: 'definitionPartName',
                ellipsis: true,
            },
            {
                title: <span title="是否可见">是否可见</span>,
                dataIndex: 'isShow',
                key: 'isShow',
                width:"80px",
                ellipsis: true,
                render: text => isShowList.find(item => item.id == text).dictLabel
            },
            {
                title: <span title="是否生效">是否生效</span>,
                dataIndex: 'isEffective',
                key: 'isEffective',
                width:"80px",
                ellipsis: true,
                render: text => isEffectiveList.find(item => item.id == text).dictLabel
            },
            // {
            //     title: '约束条件',
            //     dataIndex: 'propertyConstraint',
            //     key: 'propertyConstraint',
            //     ellipsis: true,
            //     render:text=><Popover trigger="hover" title="约束条件" content={(
            //         <div>
            //           <p>是否必要:{text&&text.required?isRequiredList.find(item=>item.id==text.required).dictLabel:'无'}</p>
            //           <p>小数位数:{text&&text.required?text.precision:'无'}</p>
            //           <p>最小值:{text&&text.min?text.min:'无'}</p>
            //           <p>最大值:{text&&text.max?text.max:'无'}</p>
            //           <p>正则规则:{text&&text.regExp?text.regExp:'无'}</p>

            //         </div>
            //       )}><a href="javascript:void(0)">悬浮查看</a></Popover>
            // },
            // {
            //     title: '备注',
            //     dataIndex: 'remark',
            //     key: 'remark',
            //     ellipsis: true,
            // },
            {
                title: '操作',
                key: '操作',
                width: "150px",
                render: (text, record) => <span className="operate"><a onClick={(e) => this.editCusProps(e, record)}><Icon type="edit" /><span>编辑</span></a> <a onClick={(e) => this.deleteCusProps(e, record)}><Icon type="delete" /><span>删除</span></a></span>,
            },
        ];
        return (
            <div className="libary absMiddle">
                <div className="libaryNav absMiddle">
                    <div className="absMiddle navLeft">
                        <div className="logo"><Icon type="global" /></div>
                        <div className="title">智能桥梁设计系统管理平台</div>
                    </div>
                    <div className="absMiddle navRight">
                        <div>admin</div>
                    </div>
                </div>
                <div className="libaryContent absMiddle">
                    <div className="libaryTreeBox ">
                        <StructureTree selectedKeys={selectedKeys} treeData={treeData} expandedKeys={expandedKeys} onSelect={this.onSelect} onLoaded={(context) => {
                            this.setState({
                                structureTreeContext: context
                            })
                        }}></StructureTree>
                    </div>
                    <div className="tableMain absMiddle">
                        <div className="title absMiddle">
                            <div>数据列表</div>
                            <div className="btnBox"><Button onClick={this.massDelete} disabled={!selectedRowKeys || !selectedRowKeys.length} icon="delete" type='danger'>删除</Button><Button onClick={this.addCusProp} disabled={!definitionTreeId} icon="plus" type="primary">添加</Button></div>
                        </div>
                        <div className="absMiddle tableBox">
                            <Table loading={tloading} pagination={false} rowKey={record => record.id} scroll={{ y: 560 }} rowSelection={rowSelection} columns={columns} dataSource={data} />
                        </div>
                    </div>
                </div>
                <ToolConfigModals
                    onLoaded={context => {
                        this.setState({ modalContext: context })
                    }}
                    parent={this}
                    refresh={this.refresh}
                />
            </div>
        )
    }
}
export default connect(
    ({
        dict: { dictlist },
    }) => ({
        dictlist
    })
    , dispatch => ({
        getStructureTree: (values) => dispatch({
            type: 'structure/getCateTree',
            payload: values
        }),
        cusPropsList: (values) => dispatch({
            type: 'cusProps/cusPropsList',
            payload: values
        }),
        deleteCusProps: (values, onSuccess, onError) => dispatch({
            type: 'cusProps/deleteCusProps',
            payload: {
                values, onSuccess, onError
            }
        }),
    })
)(Form.create('CusProps', {

})(CusProps));